import axios from 'axios';
import apiClient from './axios';
import mockService from '../utils/mockService';

// 认证相关的接口
export interface LoginRequest {
  username: string;
  password: string;
  remember?: boolean;
  captcha?: string;
}

// 登录响应接口
export interface LoginResponse {
  success: boolean;
  message: string;
  data?: {
    user: {
      id: string;
      username: string;
      name: string;
      email: string;
      role: string;
      avatar?: string;
    };
    token: string;
  };
}

// 注册请求接口
export interface RegisterRequest {
  username: string;
  password: string;
  confirmPassword: string;
  name: string;
  email: string;
  role?: string;
}

// 创建认证相关API请求服务
const authApi = {
  // 登录方法
  login: async (loginData: LoginRequest): Promise<LoginResponse> => {
    try {
      // 创建一个新对象，排除 remember 参数
      const { remember, ...loginParams } = loginData;
      
      // 只发送不包含 remember 的参数给后端
      const response = await apiClient.post<LoginResponse>('/auth/login', loginParams);
      
      // 如果登录成功，保存token和用户信息
      if (response.data.success && response.data.data) {
        // 如果勾选了"记住我"，使用localStorage，否则使用sessionStorage
        const storage = remember ? localStorage : sessionStorage;
        
        storage.setItem('token', response.data.data.token);
        storage.setItem('userInfo', JSON.stringify(response.data.data.user));
      }
      
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        // 返回服务器的错误响应
        return error.response.data as LoginResponse;
      }
      
      // 网络错误等其他情况
      return {
        success: false,
        message: '登录请求失败，请检查网络连接或服务器状态'
      };
    }
  },

  // 注册方法
  register: async (registerData: RegisterRequest): Promise<LoginResponse> => {
    try {
      const response = await apiClient.post<LoginResponse>('/auth/register', registerData);
      
      // 如果注册成功且返回了token，保存token和用户信息
      if (response.data.success && response.data.data) {
        localStorage.setItem('token', response.data.data.token);
        localStorage.setItem('userInfo', JSON.stringify(response.data.data.user));
      }
      
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error) && error.response) {
        return error.response.data as LoginResponse;
      }
      
      return {
        success: false,
        message: '注册请求失败，请检查网络连接或服务器状态'
      };
    }
  },

  // 获取当前用户信息
  getCurrentUser: () => {
    const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo');
    return userInfo ? JSON.parse(userInfo) : null;
  },

  // 检查用户是否已登录
  isAuthenticated: (): boolean => {
    return localStorage.getItem('token') !== null || sessionStorage.getItem('token') !== null;
  },

  // 登出方法
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('userInfo');
    // 可选：重定向到登录页
    window.location.href = '/login';
  },

  // 获取验证码图片
  getCaptcha: async (): Promise<string> => {
    // 检查是否应该使用模拟数据
    if (mockService.shouldUseMock('/auth/captcha')) {
      try {
        const mockBlob = await mockService.mockCaptcha();
        return URL.createObjectURL(mockBlob);
      } catch (error) {
        console.error('获取模拟验证码失败:', error);
        return '';
      }
    }
    
    let retryCount = 0;
    const maxRetries = 3;
    
    const attemptFetch = async (): Promise<string> => {
      try {
        const response = await apiClient.get('/auth/captcha', {
          responseType: 'blob',
          timeout: 10000 // 10秒超时
        });
        
        if (response.data) {
          return URL.createObjectURL(response.data);
        }
        throw new Error('未能获取到验证码数据');
        
      } catch (error) {
        if (retryCount < maxRetries) {
          retryCount++;
          console.log(`验证码获取失败，正在进行第${retryCount}次重试...`);
          // 指数退避策略，每次重试等待时间增加
          await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
          return attemptFetch();
        }
        
        console.error('获取验证码失败，已达到最大重试次数:', error);
        
        // 如果服务器暂时不可用，返回空字符串
        return '';
      }
    };
    
    return attemptFetch();
  }
};

export default authApi; 